﻿using EFCore事务示例同时向两张表新增数据.Models;

namespace EFCore事务示例同时向两张表新增数据.Data
{
    public class ProcessData
    {
        public ProcessData(MyContext context)
        {
            Context = context;
        }

        public MyContext Context { get; }

        
        /// <summary>
        /// 添加数据,使用事务示例
        /// </summary>
        /// <returns></returns>
        public int AddData()
        {
            //模拟学生对象
            //模拟班级对象
            Student student = new Student
            {
                Name = "张三",
                MyClassId = 1,
            };
            MyClass myClass = new MyClass
            {
                Name = "一班",
            };

            //核心代码开启事务Context.Database.BeginTransaction()
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    Context.Students.Add(student);//向学生表插入数据
                    Context.SaveChanges();
                                        
                    //throw new Exception("假设出错");//假设出错
                    
                    Context.MyClasses.Add(myClass);//向班级表插入数据
                    Context.SaveChanges();
                    
                    tran.Commit();//提交事务
                    return 1;
                }
                catch (Exception)
                {
                    tran.Rollback();//回滚事务
                    throw new Exception("事务回滚");
                }
            }
        }
    }
}
